package com.example.cyberqueueandroid;

import com.tauproject.EZQueue.R;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
	public Intent mServiceIntent = null;
	private WebView mWebView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initWebView();

		String url = "";

		Intent intent = getIntent();
		if (intent.getAction() == Intent.ACTION_VIEW) {
			url = intent.getData().toString();
		} else if (SharedData.POS_MANAGER.getUserPosition() >= 0) {
			url = SharedData.URI + "/user_page?queue_id=" + SharedData.POS_MANAGER.getQueueID();
		} else {
			url = SharedData.URI;
		}

		mWebView.loadUrl(url);

		stopCQService();

		startCQService();
	}

	private void startCQService() {
		mServiceIntent = new Intent(this, NotifierService.class);
		startService(mServiceIntent);
	}

	public void initWebView() {
		mWebView = (WebView) findViewById(R.id.webview);
		WebSettings settings = mWebView.getSettings();
		settings.setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new CyberQueueWebViewClient());
		SharedData.POS_MANAGER = new PositionsManager(mWebView);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void stopCQService() {
		if (mServiceIntent != null) {
			stopService(mServiceIntent);
			mServiceIntent = null;
		}
	}

	public void showAlert() {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle("EZQueue");
		alertDialog.setMessage("it's your turn");
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		alertDialog.show();
	}

}
